package org.ytor.core.sysapi.permission.api;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;
import org.ytor.common.exception.BaseException;
import org.ytor.common.model.R;
import org.ytor.common.util.Strs;
import org.ytor.common.util.bean.Beans;
import org.ytor.core.BaseController;
import org.ytor.core.sysapi.permission.logic.SysPermissionLogic;
import org.ytor.core.sysapi.permission.model.SysPermission;
import org.ytor.core.sysapi.permission.repository.SysPermissionRepository;
import org.ytor.core.sysapi.permission.req.SysPermissionReq;
import org.ytor.core.sysapi.permission.resp.SysPermissionResp;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * created by System on 2025年5月22日 20:45:43
 * <br/>
 * SysPermission表控制器
 * <br/>
 */
@RestController
@RequestMapping("/rbac/sysPermission")
@Tag(name = "资源表")
public class SysPermissionController extends BaseController<SysPermission, SysPermissionLogic, SysPermissionRepository> {

    /**
     * 查询资源的树形数据
     */
    @GetMapping("/tree")
    @Operation(summary = "查询资源数据", description = "查询资源的树形数据")
    public List<Map<String, Object>> tree(String permissionName) {
        return logic.tree(permissionName);
    }

    /**
     * 根据id查询数据
     */
    @GetMapping("/queryById")
    @Operation(summary = "根据id查询", description = "根据id查询数据")
    protected R<SysPermissionResp> queryById(String id) {
        SysPermission sysPermission = repository.queryById(id);
        return R.success(sysPermission.toResp());
    }

    /**
     * 新增或编辑数据
     */
    @PostMapping("/addOrUpdate")
    @Operation(summary = "新增或编辑", description = "根据有无主键id,新增或编辑数据")
    protected R<String> addOrUpdate(@RequestBody SysPermissionReq sysPermissiondata) {
        SysPermission sysPermission = Beans.copyProperties(sysPermissiondata, SysPermission.class);
        if (Strs.isEmpty(sysPermission.getPid())) {
            sysPermission.setPid("0");
        }
        repository.insertOrUpdate(sysPermission);
        return R.success(sysPermissiondata.getId() == null ? "新增成功" : "编辑成功");
    }

    /**
     * 删除
     */
    @DeleteMapping("/delete/{ids}")
    @Operation(summary = "删除", description = "根据id删除数据")
    protected R<String> delete(@Parameter(description = "主键id") @PathVariable String ids) {
        if (Strs.isEmpty(ids)) {
            throw new BaseException("删除接口的ids不能为空");
        }
        List<String> idList = Arrays.asList(ids.split(","));
        repository.deleteById(idList);
        return R.success("删除成功");
    }

    /**
     * 根据pid查询子数据
     */
    @GetMapping("/queryByPid")
    @Operation(summary = "根据pid查询子数据", description = "根据pid查询子数据")
    protected List<SysPermissionResp> queryByPid(String pid) {
        return logic.queryByPid(pid);
    }

}